from config import MQTT_ADDR, ENV_REPORT_TOPIC
from hbmqtt.client import MQTTClient, ClientException
from hbmqtt.mqtt.constants import QOS_0, QOS_1, QOS_2
import common
import datetime


async def mqtt_client_poll():
    c = MQTTClient()
    await c.connect(MQTT_ADDR)
    await c.subscribe([(ENV_REPORT_TOPIC, QOS_0),])
    try:
        while True:
            msg = await c.deliver_message()
            packet = msg.publish_packet
            topic = packet.variable_header.topic_name
            msg_content = packet.payload.data.decode('utf8')
            await process_mqtt_msg(topic, msg_content)
    except ClientException as ce:
        print("error:", ce)
        await c.disconnect()

async def process_mqtt_msg(topic, msg_content):
    msg = json.loads(msg_content)
    redis = await common.get_redis()
    await redis.set("aihome:status", msg_content)
    stamp = datetime.datetime.now()
    msg['stamp'] = str(stamp)
    length = await redis.rpush("aihome:env:datas", [json.dumps(msg),])
    if length > 1000:
        await redis.lpop("aihome:env:datas")

async def mqtt_publish(topic, msg):
    c = MQTTClient()
    await c.connect(MQTT_ADDR)
    msg = await c.publish(topic, bytes(msg, 'utf8'), qos=QOS_1)
    await c.disconnect()

tasks = [mqtt_client_poll,]
